package com.nj9you.wxpay.config;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.PropertyConfigurator;

import com.nj9you.wxpay.dao.Dao;

public class WXProperty {

    private static final Properties sProperties;
    static {
        sProperties = new Properties();
        try {
            sProperties.load(WXProperty.class.getResourceAsStream("/wxpay.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String filePath = Dao.class.getResource("/log4j.properties").getFile();
            PropertyConfigurator.configure(filePath);
        } catch(Exception e) {
        }
    }

    public static String get(String key) {
        if (sProperties != null) {
            return sProperties.getProperty(key);
        }
        return null;
    }

    public static String getNotifyUrl(HttpServletRequest request) {
        String notifyUrl = get("notify_url");
        if (notifyUrl == null) {
            return null;
        }
        if (!notifyUrl.startsWith("http://") && !notifyUrl.startsWith("https://")) {
            String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            if (notifyUrl.startsWith("/")) {
                notifyUrl = serverUrl + notifyUrl;
            } else {
                notifyUrl = serverUrl + "/" + notifyUrl;
            }
        }
        return notifyUrl;
    }
}
